#!/usr/bin/env python
#coding=utf-8

import os, sys
import time
import tesserocr
import pyperclip

from pyinotify import *
from PIL import Image

WATCH_PATH = "/home/fengbo/图片"
if not WATCH_PATH:
    print("The WATCH_PATH setting MUST be set.")
    sys.exit()
else:
    if os.path.exists(WATCH_PATH):
        print('Found path: path=%s.' % (WATCH_PATH))
    else:
        print('The path NOT exists, watching stop now: path=%s.' % (WATCH_PATH))
        sys.exit()

def image2word(path):
    try:
        time.sleep(0.1)
        image = Image.open(path)
        words = tesserocr.image_to_text(image, "chi_sim")
        print(words)
        pyperclip.copy(words)
        time.sleep(1)
        os.remove(path)
    except (OSError, NameError):
        print("os error")

class EventHandler(ProcessEvent):
    def process_IN_CREATE(self, event):
        text = os.path.join(event.path, event.name)
        image2word(text)

def auto_compile(path='.'):
    wm = WatchManager()
    mask = IN_CREATE
    notifier = ThreadedNotifier(wm, EventHandler())
    notifier.start()
    wm.add_watch(path, mask, rec=True, auto_add=True)
    while True:
        try:
            notifier.process_events()
            if notifier.check_events():
                notifier.read_events()
        except KeyboardInterrupt:
            notifier.stop()
            break

if __name__ == "__main__":
    auto_compile(WATCH_PATH)
